<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves plain size="small" class="filter-item btn" type="success" icon="el-icon-plus" @click="handleCreate">
        新增补量规则
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" align="center" width="60" type="index" />
      <el-table-column label="渠道号" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.qudao }}</span>
        </template>
      </el-table-column>
      <el-table-column label="补量比例" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.price + '%' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" plain size="small" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" plain size="small" @click="handleDel(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" class="pageShow" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <pagination v-show="total > 0" layout="prev, pager, next" :small="true" class="pageHidden" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :width="dialogWidth">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" class="fullwidth">
        <el-form-item label="渠道号" prop="qudao">
          <el-select v-model="temp.qudao" style="width: 100%" clearable filterable placeholder="请选择渠道号" class="filter-item" :disabled="dialogStatus==='update'">
            <el-option key="-1" label="全局" value="全局" />
            <el-option v-for="(item, index) in qudaoArr" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="补量比例" prop="price">
          <el-input v-model="temp.price" placeholder="请输入1到100的整数" />
        </el-form-item>
        <div style="text-align: right">
          <el-button plain size="small" @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" plain size="small" @click="dialogStatus==='create'?createData():updateData()">
            确定
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, del, fetchQudao, create, update } from '@/api/admin/dosage'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox, Message } from 'element-ui'

export default {
  name: 'Dosage',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      qudaoArr: [],
      listQuery: {
        page: 1,
        limit: 20
      },
      temp: {
        qudao: '',
        price: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogWidth: 0,
      textMap: {
        update: '修改补量规则',
        create: '新增补量规则'
      },
      rules: {
        qudao: [{ required: true, message: '渠道号是必需的', trigger: 'change' }],
        price: [
          { required: true, message: '补量数值是必需的', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (/^([1-9]|[1-9]\d|100)$/.test(value) === false) {
                callback(new Error('请输入1到100的整数'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getQudao()
    this.getList()
    this.setDialogWidth()
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setDialogWidth()
      })()
    }
  },
  methods: {
    getQudao() {
      fetchQudao().then(response => {
        this.qudaoArr = response.channel
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    setDialogWidth() {
      const val = document.body.clientWidth
      const def = 550 // 默认宽度
      if (val < def) {
        this.dialogWidth = '100%'
      } else {
        this.dialogWidth = def + 'px'
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        qudao: '',
        price: ''
      }
    },
    handleCreate() {
      this.getQudao()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            if (response.code === 1) {
              this.handleFilter()
              this.dialogFormVisible = false
              Message({
                message: response.msg || '添加成功',
                type: 'success',
                duration: 2000
              })
            } else {
              Message({
                message: response.msg || '添加失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.qudao = row.qudao
      this.temp.price = row.price
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.temp).then(response => {
            if (response.code === 1) {
              this.dialogFormVisible = false
              this.getList()
              Message({
                message: response.msg || '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              Message({
                message: response.msg || '修改失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDel(row) {
      MessageBox.confirm('确定要删除吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          if (response.code === 1) {
            this.handleFilter()
            Message({
              message: response.msg || '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            Message({
              message: response.msg || '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0;
    font-size: 16px;
    color: #ccc;
    cursor: pointer;
    user-select: none;
  }
  .pageHidden{
    display: none;
  }
  .btn{
    margin-left:0;
  }
  .fullwidth{
    width: 400px;
    margin-left:50px;
  }
  @media (max-width:550px) {
    .pageShow {
      display: none;
    }
    .pageHidden {
      display: block;
    }
    .fullwidth{
      width:100%;
      margin-left:0;
    }
  }
</style>
